package edu.hit.crawler.util;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.io.Writable;

import edu.hit.crawler.util.RobotsEntry;

public class RobotsRulesWritable implements Writable {

	//private RobotsRulesWritable rw = new RobotsRulesWritable();
	private List<RobotsEntry> rules = new ArrayList<RobotsEntry>();
	
	public RobotsRulesWritable() {
		
	}
	
	/*public RobotsRulesWritable (RobotsRulesWritable rw) {
		this.rw = rw;
	}*/
	
	public RobotsRulesWritable(List<RobotsEntry> rules) {
		if(this.rules != null && this.rules.size() != 0) {
			this.rules.clear();
		}
		
		this.rules = rules;
	}
	
	@Override
	public void readFields(DataInput in) throws IOException {
		
		if(rules == null) { 
			rules = new ArrayList<RobotsEntry>();
		} else {
			rules.clear();
		}	
		
		int size = in.readInt();
		List<RobotsEntry> robotsRules = new ArrayList<RobotsEntry>();
		boolean allowed = false;
		String prefix = "";
		RobotsEntry re = null;
		for(int i = 0; i < size; i++){
			prefix = in.readUTF();
			allowed = in.readBoolean();
			re = new RobotsEntry(prefix, allowed);
			
			robotsRules.add(re);
		}
	}

	@Override
	public void write(DataOutput out) throws IOException {
	   if(this.rules != null) {
		   out.writeInt(rules.size());
		   
		   for(int i = 0; i < rules.size(); i++) {
			   out.writeUTF(rules.get(i).getPrefix());
			   out.writeBoolean(rules.get(i).getAllowed());
		   }
	   }
	}	
}
